package com.dwjm.shop.goods;

import com.dwjm.shop.Merchant.MerchantDao;
import com.dwjm.shop.Merchant.MerchantDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

@WebServlet("/addGoods")
@MultipartConfig
public class GoodsHandler extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        
        // 添加调试日志
        System.out.println("接收到商品添加请求");
        
        String title = req.getParameter("title");
        String price = req.getParameter("price");
        String descr = req.getParameter("descr");
        String img = req.getParameter("img");
        String mid = req.getParameter("mid");
        
        // 打印接收到的参数
        System.out.println("标题: " + title);
        System.out.println("价格: " + price);
        System.out.println("描述: " + descr);
        System.out.println("图片: " + img);
        System.out.println("商家ID: " + mid);
        
        try {
            Goods goods = new Goods(null, title, new BigDecimal(price), descr, img, 0, Integer.parseInt(mid));
            GoodDao goodDao = new GoodDaoImpl();
            int i = goodDao.addGoods(goods);
            System.out.println("数据库操作结果: " + i);
            if(i == 1){
                resp.getWriter().write("Y");
            }else {
                resp.getWriter().write("N");
            }
        } catch (Exception e) {
            System.out.println("添加商品时发生错误: " + e.getMessage());
            e.printStackTrace();
            resp.getWriter().write("N");
        }
    }
}